import React from 'react'
import styles from './index.module.css'
import PropTypes from 'prop-types'


export default class Sticky extends React.Component {

  // 创建ref对象
  placeholder = React.createRef()
  content = React.createRef()

  // 滚动处理函数
  handleScroll = () => {
    // 获取 DOM 元素
    const placeholderEl = this.placeholder.current
    const connentEl = this.content.current
    
    // 通过 getBoundingClientRect() 方法得到筛选栏占位元素当前位置
    // 注意：这里要拿到的是 placeholderEl 占位盒子的DOM
    // const {top:c} = connentEl.getBoundingClientRect()
    // const { top:p } = placeholderEl.getBoundingClientRect()
    const { top } = placeholderEl.getBoundingClientRect()
    // console.log(c,p) // bottom/height/left/right/top/width/x/y
    if (top < 0) {
      // connentEl.classList.add(styles.fixed)
      connentEl.className  = `${styles.fixed}`
      placeholderEl.style.height = `${this.props.height}px`
    } else {
      connentEl.classList.remove(styles.fixed)
      placeholderEl.style.height = '0px'
    }
  }

  // 监听浏览器的滚动事件
  componentDidMount() {
    // console.log(this.content.current);
    window.addEventListener('scroll', this.handleScroll)
  }

  // 销毁自定义监听事件
  componentWillUnmount() {
    window.removeEventListener('scroll',this.handleScroll)
  }

  render() {
    return (
      // 占位符
      <div>
        {/* 占位盒子 */}
        <div ref={this.placeholder}></div>
        {/* 固定定位组件 */}
        <div ref={this.content}>
          {this.props.children}
        </div>
      </div>
    )
  }
}

// 组件 props 校验
Sticky.propTypes = {
  height: PropTypes.number.isRequired
}